<template>
  <div>

    <!-- 搜索区域 -->
    <el-card>
      <div>
        <h3>{{ queryParams }}</h3>
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto">
          <el-form-item label="分类名称" prop="category_name">
            <!-- @keyup.enter="handleQuery" -->
            <el-input placeholder="分类名称" v-model="queryParams.category_name" clearable />
          </el-form-item>

          <el-form-item label="是否显示" prop="is_show">
            <el-select placeholder="全部" clearable v-model="queryParams.is_show" style="width: 100px">
              <el-option label="全部" value="" />
              <el-option label="显示" :value="1" />
              <el-option label="不显示" :value="0" />
            </el-select>
          </el-form-item>

          <el-form-item label="创建时间" prop="add_date">
            <el-date-picker :editable="false" v-model="queryParams.add_date" type="daterange" range-separator="~"
              start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" />
          </el-form-item>

          <el-form-item class="search-buttons">
            <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
            <el-button icon="refresh" @click="handleResetQuery(queryFormRef)">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 表格列表 -->
    <el-card>
      <!-- 添加 -->
      <el-button type="success" size="small" :icon="Plus" @click="add">添加分类</el-button>
      <el-button type="danger" size="small" :icon="Delete" @click="delSelected">删除所选分类</el-button>

      <el-table ref="elTableRef" :data="tableData" size="small" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="名称">
          <template #default="{ row }">
            <div>
              {{ row.category_name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="简介">
          <template #default="{ row }">
            <div>
              {{ row.intro }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="排序">
          <template #default="{ row }">
            <div>
              {{ row.sort }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="是否展示在前端">
          <template #default="{ row, $index }">
            <div>
              <el-tag :type="row.is_show ? 'success' : 'info'">{{ row.is_show ? '显示' : '不显示' }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="添加时间">
          <template #default="{ row }">
            <div>
              {{ formatDate(row.add_date, 'YYYY-MM-DD') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="后台发布者">
          <template #default="{ row }">
            <div>
              {{ row.nickname || '匿名' }}
            </div>
          </template>
        </el-table-column>


        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" :icon="Edit" @click="edit(row)">编辑</el-button>
            <el-button type="danger" :icon="Delete" @click="del(row)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>

      <!-- 分页 -->
      <div style="margin: 8px 0;">
        <!-- total:总记录数,default-page-size:每页显示条数 -->
        <el-pagination background v-model:current-page="page" @current-change="currentChange"
          :default-page-size="pagesize" layout="prev, pager, next,total" :total="count" />
      </div>

    </el-card>

    <!-- 添加、编辑分类的弹框 -->
    <el-dialog v-model="isShowDialog" :title="(operate === 'add' ? '添加' : '编辑') + '分类'">
      <el-form ref="ruleFormRef" :rules="rules" :model="formData" style="max-width: 800px" label-width="auto"
        label-position="right">
        <el-form-item label="分类名称" prop="category_name">
          <el-input autocomplete="off" placeholder="分类名称" v-model="formData.category_name" />
        </el-form-item>

        <el-form-item label="是否显示" prop="is_show">
          <el-switch v-model="formData.is_show" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input type="number" v-model="formData.sort" />
        </el-form-item>

        <el-form-item label="后台发布者" prop="admin_id">
          <el-select placeholder="请选择发布者" v-model="formData.admin_id">
            <!-- value：改成管理员主键，label:自定义显示名称 -->
            <el-option label="请选择" :value="0" />
            <el-option v-for="item in adminList" :key="item.admin_id" :label="item.nickname || item.username"
              :value="item.admin_id" />
          </el-select>
        </el-form-item>

        <el-form-item label="简介" prop="intro">
          <el-input v-model="formData.intro" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
            placeholder="介绍一下吧" />
        </el-form-item>

        <el-form-item label="添加时间" prop="add_date">
          <!-- :default-time="defaultTime" -->
          <el-date-picker type="datetime" :clearable="false" v-model="formData.add_date" placeholder="选择添加日期" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isShowDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确认
          </el-button>
          <el-button type="primary" @click="resetForm(ruleFormRef)">
            重置reset
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import CategoryAPI, { type Category } from '@/api/system/category.api';
import { formatDate, formatUnix } from '@/utils/index'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { useTemplateRef } from 'vue';
import moment from 'moment';
import UserAPI, { type AdminInfo } from '@/api/system/user.api';
import type { FormInstance, FormRules } from 'element-plus';



const page = ref(1) // 页码
const pagesize = ref(5) // 每页显示条数
const count = ref(0) // 分页的总记录数
const tableData = ref<Category[]>([])
const isShowDialog = ref<boolean>(false)
const queryFormRef = ref<FormInstance>()
const ruleFormRef = ref<FormInstance>()
const operate = ref<string>('add') // edit  add
const queryParams = ref({ category_name: '', is_show: '', start_date: '', end_date: "", add_date: '' })
// 表单数据
const formData = ref<Category>({
  category_name: '',
  sort: 0,
  is_show: true,
  intro: '',
  add_date: moment().format('YYYY-MM-DD HH:mm:ss'), // 或 new Date() 获取当前系统时间
  admin_id: 0
})

// 仅监听queryParams数据对象的add_date属性，分割成start_date和end_date
watch(() => {
  return queryParams.value.add_date
}, (data) => {
  console.log('watch', data)
  queryParams.value.start_date = formatUnix(data[0]) + ''
  queryParams.value.end_date = formatUnix(data[1]) + ''
})


// 自定义验证规则函数
const checkAdmin = (rule: any, value: any, callback: any) => {
  // value当前校验表单用户输入的值
  console.log('checkAdmin-value=>', value)
  if (!value) {
    // 验证失败
    return callback(new Error('必须选择一个发布者'))
  }

  // 验证成功
  callback()
}

// 自定义验证规则函数-校验用户名是否唯一
const checkUpdCategory = (rule: any, value: any, callback: any) => {
  // value当前校验表单用户输入的值 console.log('checkAdmin-value=>', value)
  // 仅编辑才调用
  if (operate.value === 'edit') {
    // callback(new Error('编辑分类名重复，请更换一个'))
    CategoryAPI.checkUpdCategoryName(formData.value.category_id as number, value).then(data => {
      // 成功
      console.log('data=>', data)
      callback() // 通过
    }).catch(err => {
      // 接口请求失败
      callback(new Error('编辑分类名重复，请更换一个' + err.message))
    })

  }

  if (operate.value === 'add') {
    callback() // 通过
  }
}

// 验证规则
const rules = reactive<FormRules<Category>>({
  category_name: [
    { required: true, message: '分类名必填', trigger: 'blur' },
    { min: 3, max: 10, message: '必须是3-10个字符', trigger: 'blur' },
    { validator: checkUpdCategory, trigger: 'blur' },
  ],
  admin_id: [
    // validator自定义规则
    { validator: checkAdmin, trigger: 'blur' },
  ],
  intro: [
    { required: true, message: '简介必填', trigger: 'blur' },
  ]
})



const adminList = ref<AdminInfo[]>([])

const elTableRefComp = useTemplateRef('elTableRef') // 绑定组件实例

onMounted(() => {
  fetchCategory()
})

// 重置搜索表单
const handleResetQuery = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  fetchCategory()
}

// 编辑弹出表单
const edit = async (row: Category) => {
  operate.value = 'edit'
  console.log(row)
  isShowDialog.value = true; // 打开弹窗
  resetForm(ruleFormRef.value) // 重置表单
  // 发送请求获取当前分类的信息，回显在表单中
  adminList.value = await UserAPI.getAdminList()
  let category = await CategoryAPI.getCategory(row.category_id as number)
  category.is_show = category.is_show ? true : false
  category.add_date = formatDate(parseInt(category.add_date))
  formData.value = category
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  queryParams.value.start_date = ''
  queryParams.value.end_date = ''
}

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 1. 验证成功
      console.log('验证成功!')
      // 转换数据库所需要的数据格式
      formData.value.is_show = formData.value.is_show ? 1 : 0
      formData.value.add_date = moment(formData.value.add_date).valueOf() / 1000 + ''
      // console.log(formData.value)
      // 2. 调用添加或编辑分类的接口
      if (operate.value === 'add') {
        await CategoryAPI.addCategory(formData.value)
      } else {
        await CategoryAPI.updCategory(formData.value)
      }

      ElMessage({
        type: 'success',
        message: (operate.value === 'add' ? '添加' : '编辑') + '分类成功'
      })
      isShowDialog.value = false
      fetchCategory()

    } else {
      // 验证失败
      console.log('error submit!', fields)
    }
  })
}

// 添加分类弹出表单
const add = async () => {
  operate.value = 'add'
  // 恢复默认值（要重置表单数据）
  resetForm(ruleFormRef.value)
  // 1. 获取管理员列表接口数据
  adminList.value = await UserAPI.getAdminList()
  // 2. 显示添加表单
  isShowDialog.value = true
}

// 删除勾选的分类
const delSelected = async () => {
  let selectedRows = elTableRefComp.value!.getSelectionRows()
  if (selectedRows.length === 0) {
    ElMessage({
      type: 'warning',
      message: '你还未选中'
    })
    return
  }
  let ids = '' // '1,7,9'
  let idsArr: number[] = []
  selectedRows.forEach((item: Category) => {
    idsArr.push(item.category_id)
    // ids += `,${item.category_id}`
  })
  // console.log(ids.substring(1))
  ids = idsArr.join(',')
  // 发送请求删除多个
  await CategoryAPI.delManyCategory(ids)
  ElMessage({
    type: 'success',
    message: '删除所选分类成功',
  })
  // 重新获取分页数据
  fetchCategory()
}

// 删除分类
const del = (row: Category) => {
  ElMessageBox.confirm(
    `你确认删除${row.category_name}吗`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      // 调用接口进行删除
      await CategoryAPI.fetchDeleteCategory(row.category_id)
      // 重新获取分页数据
      fetchCategory()

      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
    })

}

// 获取分类
const fetchCategory = async () => {
  let result = await CategoryAPI.fetchCategory({ page: page.value, pagesize: pagesize.value, ...queryParams.value })
  tableData.value = result.category
  count.value = result.count
}

// 点击分页，发送请求
const currentChange = () => {
  fetchCategory()
}

// 搜索方法,传递4个参数
const handleQuery = () => {
  fetchCategory()
}
</script>

<style scoped>
.el-card {
  margin: 10px;
}
</style>
